<?php

namespace App\Imports;


use App\Models\TakeOrderModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use stdClass;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;

class GenericImport implements ToCollection, WithMultipleSheets, WithCalculatedFormulas
{


    private $result;

    public function __construct() {
        $this->result = new stdClass;
    }

    public function collection(Collection $rows){
        $lines = [];
        $this->result->error = [];

        $head = $rows[0];
        $fee_arr = [];
        foreach ($head as $k => $v){
            if($k > 11){
                $fee_arr[$k] = $v;
            }
        }


        foreach ($rows as $k => $row) {
            if($k < 1) continue;

            $sn = $row[1];
            if($sn == ''){
                continue;
            }
            $find = TakeOrderModel::where('sn', $sn)->first();
            if(!$find){
                $this->result->error[] = '第'.$k.'行，提单号错误';
                continue;
            }


            $detail = [];  $total = 0; $price = 0;
            foreach ($fee_arr as $key => $v){
                $amount = $row[$key] ?? 0;

                if(!is_numeric($amount)) {
                    $this->result->error[] = '第'.$k.'行，'.$v.'金额错误';
                    continue;
                }

                if($v == '总金额'){
                    $total = $amount;
//                    continue;
                }
                if($v == '空运单价'){
                    $price = $amount;
//                    continue;
                }

                $detail[] = [
                    'name' => $v,
                    'amount' => $amount,
                ];

            }

            $lines[] = [
                'take_order_id' => $find->id,
                'details' => $detail,
                'total_amount' => $total,
                'price' => $price,
            ];
        }

        $this->result->lines = $lines;
    }

    public function sheets(): array {
        return [ 0 => $this];
    }

    public function get_result(){
        return $this->result;
    }


}
